import deepMerge from 'deepmerge';
import http from '@/libs/http';
import { apiConf } from '@/config';
import storage from '@/libs/storage';
import { Toast } from 'vant';
import auth from '@/service/auth';
import urls from './url-type';

const defaultConf = {
  method: 'post',
  data: {},
};
/*
 * 解析返回参数
 * */
function parseResponseData(data) {
  const responseData = {};
  Object.keys(data).forEach(item => {
    const itemData = data[item];
    const keys = item.split('_');
    const key = keys.length > 2 ? keys[1] : keys[0];

    if (Array.isArray(itemData) && itemData.length > 0) {
      if (Object.prototype.toString.call(itemData[0]) === '[object Object]') {
        responseData[key] = itemData.map(arrItem => parseResponseData(arrItem));
      } else {
        responseData[key] = data[item];
      }
    } else if (itemData && Object.prototype.toString.call(itemData) === '[object Object]') {
      responseData[key] = parseResponseData(itemData);
    } else {
      responseData[key] = data[item];
    }
  });
  return responseData;
}
/**
 * 填充 baseUrl
 *
 * @param {any} url
 * @param {any} baseUrl
 * @returns
 */
function fillBaseUrl(url, baseUrl) {
  if (url.indexOf('//') > -1) {
    return url;
  }
  baseUrl = baseUrl || apiConf.baseUrl;

  return `${baseUrl}${url}`;
}

/**
 * 组装http请求
 * @param  {[type]} urlVal [description]
 * @return {[type]}        [description]
 */
function assembleHttp(urlVal) {
  if (typeof urlVal === 'string') {
    urlVal = {
      url: `${urlVal}`,
      method: 'post'
    };
  }

  if (urlVal.baseUrl && apiConf.baseUrl !== urlVal.baseUrl) {
    urlVal.url = fillBaseUrl(urlVal.url, urlVal.baseUrl);
  } else {
    urlVal.url = fillBaseUrl(urlVal.url, urlVal.baseUrl);
  }

  return (params = {}, config = {}) => {
    config = deepMerge.all([{}, defaultConf, urlVal, config || {}], { clone: true });
    let data = { ...config.data };
    config.data = {};
    if (['post', 'put', 'patch'].indexOf(config.method) > -1) {
      const user = storage.get('user') || {};
      // formData格式数据提交
      if (params instanceof FormData) {
        params.append('userId', user.userId);
        params.append('code', user.code);
        config.data = params;
      } else {
        // config.data = Object.assign(config.data, params);
        data = { ...data, ...params };
        const version = storage.get('version') || '1.0.0';
        const code = user.code;
        const marketChannel = storage.get('marketChannel') || 'googlePlay';
        const channel = storage.get('channel') || 'Cocopeso';
        const appName = storage.get('appName') || 'MoreGold';
        const appVersion = storage.get('appVersion') || '1.0.0';
        const company = storage.get('company') || 'Funpera';
        const source = storage.get('source') || '';
        const appPackage = storage.get('appPackage') || 'com.thrift.more';
        const domain = storage.get('domain') || 'Funpera';
        let platform = 'unknown';
        const ua = navigator.userAgent;
        const isAndroid = ua.indexOf('Android') > -1 || ua.indexOf('Adr') > -1;
        const isiOS = !!ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
        if (isAndroid) platform = 'Android';
        if (isiOS) platform = 'iOS';
        config.data = Object.assign(data, {
          // 'version': version,
          // 'code': code,
          // 'platform': platform,
          // 'channel': channel,
          // 'marketChannel': marketChannel,
          // 'appName': appName,
          // 'version': appVersion,
          // 'company': company,
          // 'source': source,
          // 'appPackage': appPackage,
          // 'domain': domain,

          'petoVersionComPter': version,
          'petoCodeComPter': code,
          'petoPlatformComPter': platform,
          'petoChannelComPter': channel,
          'petoMarkChannelComPter': marketChannel,
          'petoAppNameComPter': appName,
          'petoAppVersionComPter': appVersion,
          'petoCompanyComPter': company,
          'petoSourceComPter': source,
          'petoPackagComPter': appPackage,
          'petoDomainComPter': domain,
        });
      }
    } else {
      config.params = Object.assign(config.params, params);
    }
    if(config.url.indexOf('/order/create/')!=-1){
      config.data.pSource = 'MoreGold';
    }
    config.headers = {
      cApp: storage.get('appName') || 'MoreGold',
    };

    return http(config).then(response => {
      const data = response.data;
      // parseResponseData(response.data);
      if (data && data.status === '0') {
        if (data.error === '02000114' || data.error === '01000114' || data.error === '01000113') {
          auth.expireToLogin();
          return 0;
        }
        if (response.config && response.config.showDefaultError !== false && data.error !== '01000116') {
          Toast(data.msg || 'Request error, Please try again later');
        }
      }
      return data;
    }).catch(error => Promise.reject(error));
  };
}

/**
 * 填充方法
 * @param  {[type]} apiObj [description]
 * @param  {[type]} urls   [description]
 * @return {[type]}        [description]
 */
function fillMethods(apiObj, urls) {
  const urlKeys = Object.keys(urls);

  urlKeys.forEach(urlKey => {
    const urlVal = urls[urlKey];
    if (typeof urlVal === 'string') {
      apiObj[urlKey] = assembleHttp(urlVal);
    } else if (urlVal.url) {
      apiObj[urlKey] = assembleHttp(urlVal);
    } else {
      apiObj[urlKey] = {};
      fillMethods(apiObj[urlKey], urlVal);
    }
  });
}

/**
 * Api 类
 */
class Api {
  /**
   * 作为Vue插件进行安装，挂载到Vue.prototype
   */
  install(Vue) {
    Vue.prototype.$api = this;
  }
}

fillMethods(Api.prototype, urls);


export default new Api(http);
